﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UDS.Web.UI.Controls
{
    public class RequiredTextBox : TextBox
    {
        private RequiredFieldValidator _validator;

        /// <summary>
        /// Get or set a value indicating whether the text content is required.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue(true)]
        public bool Required
        {
            get;
            set;
        }

        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue("(*)")]
        public string MissingErrorMessage
        {
            get;
            set;
        }

        /// <summary>
        /// Get or set the CSS class for the error message.
        /// </summary>
        [PersistenceMode(PersistenceMode.Attribute)]
        [DefaultValue("errorMsg")]
        public string ErrorCssClass
        {
            get;
            set;
        }

        public RequiredTextBox()
        {
            Required = true;
            MissingErrorMessage = "(*)";
            ErrorCssClass = "errorMsg";
        }

        /// <summary>
        /// Init the control
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            if (Required)
            {
                _validator = new RequiredFieldValidator();
                _validator.ControlToValidate = ID;
                InitValidator(_validator, MissingErrorMessage, ErrorCssClass);

                Controls.Add(_validator);
            }

            base.OnInit(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            if (Required)
            {
                Debug.Assert(_validator != null);

                writer.WriteLine();
                _validator.RenderControl(writer);
            }
        }

        internal static void InitValidator(BaseValidator validator, string errorMsg, string css)
        {
            validator.Display = ValidatorDisplay.Dynamic;
            validator.EnableClientScript = true;
            validator.Enabled = true;
            validator.ErrorMessage = errorMsg;
            validator.CssClass = css;
        }
    }
}
